package com.xiaobaibai.security.token.config;

import com.xiaobaibai.security.common.HttpFailureHandler;
import com.xiaobaibai.security.common.PropertiesInfo;
import com.xiaobaibai.security.token.filter.No2JwtAuthenticationFilter;
import com.xiaobaibai.security.token.filter.No3JwtAuthenticationFilter;
import com.xiaobaibai.security.token.provider.JwtAuthenticationProvider;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.web.HttpSecurityBuilder;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

//@Configuration
public class No3TokenConfig<T extends No3TokenConfig<T, B>, B extends HttpSecurityBuilder<B>>
        extends AbstractHttpConfigurer<T, B> {

    private JwtAuthenticationProvider jwtAuthenticationProvider;

    private AuthenticationSuccessHandler authenticationSuccessHandler;

    private PropertiesInfo propertiesInfo;

    public No3TokenConfig(){
    }

    @Override
    public void configure(B http) throws Exception {
        //因为继承了抽象类,所以这里必须要传个参数,就这样写了
        No3JwtAuthenticationFilter no3JwtAuthenticationFilter = new No3JwtAuthenticationFilter(http.getSharedObject(AuthenticationManager.class));
//        no3JwtAuthenticationFilter.setAuthenticationManager(http.getSharedObject(AuthenticationManager.class));
        no3JwtAuthenticationFilter.setAuthenticationFailureHandler(new HttpFailureHandler());
        no3JwtAuthenticationFilter.setPropertiesInfo(propertiesInfo);
        no3JwtAuthenticationFilter.setAuthenticationSuccessHandler(authenticationSuccessHandler);

        //把此filter放入容器,然后返回放入容器后的对象,这样@PostConstruct方法才会执行(推荐多用@Component)
        No3JwtAuthenticationFilter filter =
                postProcess(no3JwtAuthenticationFilter);

        http.authenticationProvider(jwtAuthenticationProvider)
                .addFilterAfter(filter, UsernamePasswordAuthenticationFilter.class);
    }

//    public No3TokenConfig<T, B> tokenSuccessHandler(AuthenticationSuccessHandler successHandler){
//        no3JwtAuthenticationFilter.setAuthenticationSuccessHandler(successHandler);
//        return this;
//    }

    public No3TokenConfig<T, B> setAuthenticationSuccessHandler(AuthenticationSuccessHandler authenticationSuccessHandler) {
        this.authenticationSuccessHandler = authenticationSuccessHandler;
        return this;
    }

    public No3TokenConfig<T, B> setJwtAuthenticationProvider(JwtAuthenticationProvider jwtAuthenticationProvider){
        this.jwtAuthenticationProvider=jwtAuthenticationProvider;
        return this;
    }

    public No3TokenConfig<T, B> setPropertiesInfo(PropertiesInfo propertiesInfo) {
        this.propertiesInfo = propertiesInfo;
        return this;
    }
}
